package com.maxd.controller.statistics;

import com.maxd.adapter.IgnoreSecurity;
import com.maxd.error.Result;
import com.maxd.error.ResultUtil;
import com.maxd.model.*;
import com.maxd.respository.cash.CashJpaRepository;
import com.maxd.respository.cash.CashRepository;
import com.maxd.respository.common.CommonRepository;
import com.maxd.respository.jifen.JiFenRepository;
import com.maxd.respository.order.OrderJpaRepository;
import com.maxd.respository.order.OrderRepository;
import com.maxd.respository.userinfo.UserJpaRepository;
import com.maxd.respository.userinfo.UserLogRepository;
import com.maxd.respository.userinfo.UserRepository;
import com.maxd.service.helpTask.HelpSendOrderService;
import com.maxd.service.helpTask.HelpTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.web.bind.annotation.*;
import weixin.popular.util.JsonUtil;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(value = "数据统计中心", tags = {"数据统计中心"})
@RequestMapping(value = "/statistics")
public class StatisticsController {
    @Autowired
    private OrderJpaRepository orderJpaRepository;
    @Autowired
    private UserJpaRepository userJpaRepository;
    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private CashJpaRepository cashJpaRepository;
    @Autowired
    private CashRepository cashRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private JiFenRepository jiFenRepository;
    @Autowired
    private HelpTaskService helpTaskService;
    @Autowired
    private HelpSendOrderService helpSendOrderService;
    @Autowired
    private CommonRepository commonRepository;
    @Autowired
    private UserLogRepository userLogRepository;


    @IgnoreSecurity
    @GetMapping("/selectsStatistics")
    @ApiOperation("统计")
    public Result selectsStatistics(String time,String relationId){
        //粉丝订单数
        Integer invitationCount = orderRepository.selectOrdersCountByTimeAndInvitation(time, relationId);
        Integer invitationsCount = orderRepository.selectOrdersCountByTimeAndInvitations(time, relationId);
        Integer invitationCounts=invitationCount+invitationsCount;
        //自己订单数
        Integer relationCount = orderRepository.selectOrdersCountByTimeAndRelationId(time, relationId);
        //订单笔数数
        Integer ordersCount=invitationCount+invitationsCount+relationCount;
        //我的销售
        BigDecimal invitationPrice = orderRepository.selectOrdersPriceByTimeAndInvitation(time, relationId);
        BigDecimal invitationsPrice = orderRepository.selectOrdersPriceByTimeAndInvitations(time, relationId);
        BigDecimal invitationPrices=invitationPrice.add(invitationsPrice);
        //粉丝销售
        BigDecimal relationPrice = orderRepository.selectOrdersPriceByTimeAndRelationId(time, relationId);
        //总销售额度
        BigDecimal ordersPrice=relationPrice.add(invitationPrice).add(invitationsPrice);
        //我的收益
        BigDecimal invitationMoney = orderRepository.selectOrdersMoneyByTimeAndInvitation(time, relationId);
        BigDecimal invitationsMoney = orderRepository.selectOrdersMoneyByTimeAndInvitations(time, relationId);
        BigDecimal invitationMoneys=invitationMoney.add(invitationsMoney);
        //粉丝收益
        BigDecimal relationMoney = orderRepository.selectOrdersMoneyByTimeAndRelationId(time, relationId);
        //总收益
        BigDecimal ordersMoney=relationMoney.add(invitationMoney).add(invitationsMoney);
        //专属粉丝
        int zhiCount = userRepository.selectUserByZhiCountByTime(relationId, time);
        //其他粉丝
        int feiCount = userRepository.selectUserByFeiCountByTime(relationId, time);
        //全部粉丝
        int count=zhiCount+feiCount;
        Map<String,Object> result=new HashMap<>();
        result.put("invitationCounts",invitationCounts);
        result.put("relationCounts",relationCount);
        result.put("ordersCount",ordersCount);
        result.put("invitationPrices",invitationPrices);
        result.put("relationPrice",relationPrice);
        result.put("ordersPrice",ordersPrice);
        result.put("invitationMoneys",invitationMoneys);
        result.put("relationMoney",relationMoney);
        result.put("ordersMoney",ordersMoney);
        result.put("zhiCount",zhiCount);
        result.put("feiCount",feiCount);
        result.put("count",count);
        return ResultUtil.success(result);
    }


    @GetMapping("/selectTeamUserLogCount")
    @ApiOperation("活跃统计")
    public Result selectTeamUserLogCount(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer day=0,yesterday=0,month=0,year=0;
        Calendar cal=Calendar.getInstance();
        String time = sdf.format(cal.getTime());
        //本日
        day = userLogRepository.selectUserLogCountByTime(3, time);
        cal.add(Calendar.DATE,-1);
        //昨日
        yesterday = userLogRepository.selectUserLogCountByTime(3,sdf.format(cal.getTime()));
        //本月
        month = userLogRepository.selectUserLogCountByTime(2, time);
        //今年
        year = userLogRepository.selectUserLogCountByTime(1, time);
        Map<String,Integer> map=new HashMap<>();
        map.put("day",day);
        map.put("yesterday",yesterday);
        map.put("month",month);
        map.put("year",year);
        return ResultUtil.success(map);
    }

    @GetMapping("/selectTeamUserLogList")
    @ApiOperation("活跃用户列表")
    public Result selectTeamUserLogList(Integer page,Integer size,Integer flag,String time){
        Pageable pageable = PageRequest.of(page, size);
        return ResultUtil.success(userLogRepository.selectTeamUserLogList(pageable,flag,time));
    }


    @ApiOperation("任务分析")
    @GetMapping("/taskAnalysis")
    public Result taskAnalysis(String time,Integer flag){
        Integer takeOrderCount = helpTaskService.countHelpTaskByCreateTime(time, flag);
        Double takeOrderSum = helpTaskService.sumPrice(time, flag);
        Double sendOrderSum = helpSendOrderService.sumMoneyBySend(time, flag);
        Integer sendOrderCount = helpSendOrderService.countBySend(time, flag);
        Map<String,Object> map=new HashMap<>();
        map.put("takeOrderSum",takeOrderSum==null?0.00:takeOrderSum);//发单总金额
        map.put("sendOrderSum",sendOrderSum==null?0.00:sendOrderSum);//接单总金额
        map.put("takeOrderCount",takeOrderCount==null?0:takeOrderCount);//发单数量
        map.put("sendOrderCount",sendOrderCount==null?0:sendOrderCount);//接单数量
        return ResultUtil.success(map);
    }

    @ApiOperation("财务收入统计")
    @GetMapping("/statisticsIncomeMoney")
    public Result stayMoney(String time,Integer flag){
        Double sumPrice = helpTaskService.sumPrice(time, flag);
        Double sumMoneyByProfit = helpTaskService.sumMoneyByProfit(time, flag);
        Double sumMoneyBySend = helpSendOrderService.sumMoneyBySend(time, flag);
        Map<String,Object> map=new HashMap<>();
        map.put("sumMoneyBySend",sumMoneyBySend==null?0.00:sumMoneyBySend);
        map.put("sumPrice",sumPrice==null?0.00:sumPrice);
        map.put("sumMoneyByProfit",sumMoneyByProfit==null?0.00:sumMoneyByProfit);
        return ResultUtil.success(map);
    }

    @RequestMapping(value = "/TeamOrderTotalByRelation", method = RequestMethod.GET)
    @ApiOperation("根据不同渠道统计团队订单收入")
    @ResponseBody
    public Result TeamOrderTotalByRelation(@RequestParam String relation, @RequestParam String time, @RequestParam int tk_status) {
        CommonInfo one = commonRepository.findOne(91);
        if("1".equals(one.getValue())){
            return ResultUtil.success(orderRepository.countByTnvitationAndTimeMoney(relation, time, tk_status));
        }
        String count = orderRepository.countByTnvitationAndTimeMoney(relation, time, tk_status);
        String count1 = orderRepository.countByTnvitationAndTimeMoneys(relation, time, tk_status);
        double v =0.00;
        if(count!=null){
            v=Double.parseDouble(count);
        }
        double v1 =0.00;
        if(count1!=null){
            v1=Double.parseDouble(count1);
        }
        return ResultUtil.success(v+v1);
    }

    @RequestMapping(value = "/OrderTotal", method = RequestMethod.GET)
    @ApiOperation("根据订单状态、时间统计订单收入")
    @ResponseBody
    public Result OrderTotal(@RequestParam String time, @RequestParam int tk_status) {
        return ResultUtil.success(orderRepository.countByTimeMoney(time, tk_status));
    }

    @RequestMapping(value = "/OrderTotalByFrom", method = RequestMethod.GET)
    @ApiOperation("根据订单状态、时间、渠道统计")
    @ResponseBody
    public Result OrderTotalByFrom(@RequestParam String time, @RequestParam String from, @RequestParam int tk_status) {
        return ResultUtil.success(orderRepository.countByTimeMoneyAndFromInfo(time, tk_status, from));
    }

    @RequestMapping(value = "/totalOrderByTime", method = RequestMethod.GET)
    @ApiOperation("根据时间统计订单会员结算信息 统计会员和收入")
    @ResponseBody
    public Result totalOrderByTime(@RequestParam String time, @RequestParam int tk_status) {
        List<Long> relationList = orderRepository.findRelationList(time, tk_status);
        List<invitationTotal> list = new ArrayList<>();
        for (Long l : relationList) {
            synchronized (SingleById.getById(String.valueOf(l))) {
                UserInfo userInfo = userRepository.getUserByRelationId(String.valueOf(l));
                invitationTotal invitationTotal = new invitationTotal();
                invitationTotal.setGrade(userInfo.getRelationId());
                invitationTotal.setTime(userInfo.getCreateAt());
                invitationTotal.setUserName(userInfo.getNickName());
                invitationTotal.setMoney(Math.round(Float.parseFloat(orderRepository.pubSharePreFeeCount(l, tk_status, time))));
                list.add(invitationTotal);
            }
        }
        List<invitationTotal> sortDesList = list.stream().sorted(Comparator.comparingInt(invitationTotal::getMoney).reversed()).collect(Collectors.toList());
        sortDesList.stream().forEach(s -> System.out.println(s.getMoney()));
        return ResultUtil.success(sortDesList);
    }

    @RequestMapping(value = "/getCountByTime", method = RequestMethod.GET)
    @ApiOperation("根据日期统计团长人数列表")
    @ResponseBody
    public Result totalInvitation(@RequestParam String time) {
        List<Long> invitationList = userRepository.findInvitationList(time);
        List<invitationTotal> list = new ArrayList<>();
        for (Long l : invitationList) {
            Long countByTime = userRepository.getCountByTime(String.valueOf(l), time);
            invitationTotal invitationTotal = new invitationTotal();
            invitationTotal.setGrade(String.valueOf(l));
            invitationTotal.setUserName(String.valueOf(l));
            invitationTotal.setMoney(Math.round(Float.parseFloat(String.valueOf(countByTime))));
            list.add(invitationTotal);
        }
        List<invitationTotal> sortDesList = list.stream().sorted(Comparator.comparingInt(invitationTotal::getMoney).reversed()).collect(Collectors.toList());
        sortDesList.stream().forEach(s -> System.out.println(s.getMoney()));
        return ResultUtil.success(sortDesList);
    }

    @RequestMapping(value = "/totalJiFen", method = RequestMethod.GET)
    @ApiOperation("管理平台统计 积分")
    @ResponseBody
    public Result totalJiFen(@RequestParam String time) {
        List<String> jiFenList = jiFenRepository.findJiFenList(time);
        List<invitationTotal> list = new ArrayList<>();
        for (String l : jiFenList) {
            UserInfo userInfo = userJpaRepository.findById(Long.valueOf(l)).orElse(null);
            Long countByTime = jiFenRepository.countJiFen(time, l);//统计积分数量
            String s = jiFenRepository.sumJiFen(time, l);//统计积分额度
            invitationTotal invitationTotal = new invitationTotal();
            invitationTotal.setGrade(String.valueOf(countByTime));
            assert userInfo != null;
            String number = "";
            if (userInfo != null && StringUtils.isNotEmpty(userInfo.getRelationId())){
                number = userInfo.getRelationId();
            }
            invitationTotal.setUserName(number);
            if (s != null) {
                invitationTotal.setMoney(Math.round(Float.parseFloat(s)));
            } else {
                invitationTotal.setMoney(0);
            }
            list.add(invitationTotal);
        }
        List<invitationTotal> sortDesList = list.stream().sorted(Comparator.comparingInt(invitationTotal::getMoney).reversed()).collect(Collectors.toList());
        sortDesList.stream().forEach(s -> System.out.println(s.getMoney()));
        return ResultUtil.success(sortDesList);
    }

    @RequestMapping(value = "/totalGoods", method = RequestMethod.GET)
    @ApiOperation("管理平台热门商品交易人数和交易量")
    @ResponseBody
    public Result totalGoods(@RequestParam String time) {
        List<PublisherOrderDtoBean> goodsList = orderRepository.findGoodsList(time);
        List<invitationTotal> list = new ArrayList<>();
        for (PublisherOrderDtoBean publisherOrderDtoBean : goodsList) {
            Long countByTime = orderRepository.countGoodsByItem(time, publisherOrderDtoBean.getItem_id());//统计购买量
            if (!JsonUtil.toJSONString(list).contains(publisherOrderDtoBean.getItem_title())) {
                invitationTotal invitationTotal = new invitationTotal();
                invitationTotal.setGrade(String.valueOf(publisherOrderDtoBean.getItem_id()));
                invitationTotal.setTime(String.valueOf(publisherOrderDtoBean.getItem_img()));
                invitationTotal.setUserName(publisherOrderDtoBean.getItem_title());
                invitationTotal.setMoney(Math.round(Float.parseFloat(String.valueOf(countByTime))));
                list.add(invitationTotal);
            }
        }
        List<invitationTotal> sortDesList = list.stream().sorted(Comparator.comparingInt(invitationTotal::getMoney).reversed()).collect(Collectors.toList());
        sortDesList.stream().forEach(s -> System.out.println(s.getMoney()));
        return ResultUtil.success(sortDesList);
    }

    @RequestMapping(value = "/getTuanOrderMoney", method = RequestMethod.GET)
    @ApiOperation("根据日期统计团长收入金额")
    @ResponseBody
    public Result getTuanOrderMoney(@RequestParam String time) {
        List<Long> invitationList = orderRepository.findInvitationList(time);
        List<TuanOrderTotal> list = new ArrayList<>();
        for (Long l : invitationList) {
            TuanOrderTotal tuanOrderTotal = new TuanOrderTotal();
            Long countByTime = orderRepository.countAllByInvitation(time, 12, String.valueOf(l));//付款订单数量
            Long countByTime3 = orderRepository.countAllByInvitation(time, 3, String.valueOf(l));//结算订单数量
            String invitationCountMoney = orderRepository.findInvitationCountMoney(time, 12, String.valueOf(l));
            String invitationCountMoney3 = orderRepository.findInvitationCountMoney(time, 3, String.valueOf(l));
            tuanOrderTotal.setInvitaion(l);
            tuanOrderTotal.setJieSuanNumber(countByTime3);
            tuanOrderTotal.setPaidNumber(countByTime);
            tuanOrderTotal.setTotalNumber(countByTime + countByTime3);
            if (invitationCountMoney3 != null) {
                tuanOrderTotal.setJieSuanNumber((long) Math.round(Float.parseFloat(invitationCountMoney3)));
                tuanOrderTotal.setTotalMoney((long) Math.round(Float.parseFloat(invitationCountMoney3)));
            } else {
                tuanOrderTotal.setJieSuanNumber(0L);
                tuanOrderTotal.setTotalMoney(0L);
            }
            if (invitationCountMoney != null) {
                tuanOrderTotal.setPaidNumber((long) Math.round(Float.parseFloat(invitationCountMoney)));
                tuanOrderTotal.setTotalMoney((long) Math.round(Float.parseFloat(invitationCountMoney)));
            } else {
                tuanOrderTotal.setJieSuanNumber(0L);
                tuanOrderTotal.setTotalMoney(0L);
            }
            if (invitationCountMoney != null && invitationCountMoney3 != null) {
                tuanOrderTotal.setTotalMoney((long) Math.round(Float.parseFloat(invitationCountMoney) + Float.parseFloat(invitationCountMoney3)));
            } else {
                tuanOrderTotal.setTotalMoney(0L);
            }
            list.add(tuanOrderTotal);
        }
        List<TuanOrderTotal> sortDesList = list.stream().sorted(Comparator.comparingLong(TuanOrderTotal::getTotalMoney).reversed()).collect(Collectors.toList());
        return ResultUtil.success(sortDesList);
    }

    @RequestMapping(value = "/totalRelation", method = RequestMethod.GET)
    @ApiOperation("管理平台获取所有团长 统计邀请人数")
    @ResponseBody
    public Result totalRelation() {
        List<UserInfo> allByRelationIdNotNullOrderByIdDesc = userJpaRepository.findAllByRelationIdNotNullOrderByIdDesc();
        List<invitationTotal> list = new ArrayList<>();
        for (UserInfo userInfo : allByRelationIdNotNullOrderByIdDesc) {
            synchronized (SingleById.getById(String.valueOf(userInfo.getRelationId()))) {
                invitationTotal invitationTotal = new invitationTotal();
                invitationTotal.setGrade(userInfo.getRelationId());
                invitationTotal.setTime(userInfo.getCreateAt());
                invitationTotal.setUserName(userInfo.getPhone());
                invitationTotal.setMoney(Math.round(Float.parseFloat(userRepository.getCount(userInfo.getRelationId()))));
                list.add(invitationTotal);
            }
        }
        List<invitationTotal> sortDesList = list.stream().sorted(Comparator.comparingInt(invitationTotal::getMoney).reversed()).collect(Collectors.toList());
        sortDesList.stream().forEach(s -> System.out.println(s.getMoney()));
        return ResultUtil.success(sortDesList);
    }


    @RequestMapping(value = "/totalRelationCash", method = RequestMethod.GET)
    @ApiOperation("管理平台 累计会员提现统计")
    @ResponseBody
    public Result totalRelationCash() {
        List<Long> relationList = cashRepository.findRelationList();
        List<invitationTotal> list = new ArrayList<>();
        for (Long l : relationList) {
            synchronized (SingleById.getById(String.valueOf(l))) {
                UserInfo userInfo = userRepository.getUserByRelationId(String.valueOf(l));
                invitationTotal invitationTotal = new invitationTotal();
                invitationTotal.setGrade(userInfo.getRelationId());
                invitationTotal.setTime(userInfo.getCreateAt());
                invitationTotal.setUserName(userInfo.getPhone());
                invitationTotal.setMoney(Math.round(Float.parseFloat(cashRepository.countByRelationId(String.valueOf(l)))));
                list.add(invitationTotal);
            }
        }
        List<invitationTotal> sortDesList = list.stream().sorted(Comparator.comparingInt(invitationTotal::getMoney).reversed()).collect(Collectors.toList());
        sortDesList.stream().forEach(s -> System.out.println(s.getMoney()));
        return ResultUtil.success(sortDesList);
    }

    @ApiOperation("管理平台提现统计")
    @GetMapping("/getSumMoneyByTime")
    public Result getSumMoneyByTime(@RequestParam String time) {
        Long countNumberByTime = cashRepository.getCountNumberByTime(time);//提现笔数
        String sumMoneyByTime = cashRepository.getSumMoneyByTime(time);//累计提现金额
        Long notOutMoneyByTime = cashRepository.getNotOutMoneyByTime();//待转账用户
        Map<String, String> map = new HashMap<>();
        map.put("countNumberByTime", String.valueOf(countNumberByTime));
        map.put("sumMoneyByTime", sumMoneyByTime);
        map.put("notOutMoneyByTime", String.valueOf(notOutMoneyByTime));
        return ResultUtil.success(map);
    }

    @RequestMapping(value = "/getCashList/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("用户端轮播展示用户提现")
    @ResponseBody
    public Result getCashList(@PathVariable int page, @PathVariable int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(cashJpaRepository.findAll(pageable));
    }

    @RequestMapping(value = "/getOrderList/{page}/{size}", method = RequestMethod.GET)
    @ApiOperation("用户端轮播展示订单购买")
    @ResponseBody
    public Result getOrderList(@PathVariable int page, @PathVariable int size) {
        Sort.Order order = new Sort.Order(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(page, size, Sort.by(order));
        return ResultUtil.success(orderJpaRepository.findAll(pageable));
    }

    @RequestMapping(value = "/getCountNumberByTime", method = RequestMethod.GET)
    @ApiOperation("管理平台统计根据时间统计注册用户")
    @ResponseBody
    public Result getCountNumberByTime(@RequestParam String time) {
        return ResultUtil.success(userRepository.getCountNumberByTime(time));
    }

    @RequestMapping(value = "/getCountNumberByTimeByRelationId", method = RequestMethod.GET)
    @ApiOperation("管理平台统计根据时间统计注册会员")
    @ResponseBody
    public Result getCountNumberByTimeByRelationId(@RequestParam String time) {
        return ResultUtil.success(userRepository.getCountNumberByTimeByRelationId(time));
    }

    @RequestMapping(value = "/getCountNumberByTimeRAndRelationIdIsNull", method = RequestMethod.GET)
    @ApiOperation("管理平台统计普通用户 不是会员用户")
    @ResponseBody
    public Result getCountNumberByTimeRAndRelationIdIsNull(@RequestParam String time) {
        return ResultUtil.success(userRepository.getCountNumberByTimeRAndRelationIdIsNull(time));
    }

    @RequestMapping(value = "/getCountNumberByTimeByPhone", method = RequestMethod.GET)
    @ApiOperation("管理平台统计绑定手机号用户")
    @ResponseBody
    public Result getCountNumberByTimeByPhone(@RequestParam String time) {
        return ResultUtil.success(userRepository.getCountNumberByTimeByPhone(time));
    }

    @RequestMapping(value = "/getUserTotalByPhone", method = RequestMethod.GET)
    @ApiOperation("管理平台统计微信公众号用户")
    @ResponseBody
    public Result getCountNumberByTimeByWx(@RequestParam String time) {
        return ResultUtil.success(userRepository.getCountNumberByTimeByWx(time));
    }

    @RequestMapping(value = "/getCountNumberByTimeByMp", method = RequestMethod.GET)
    @ApiOperation("管理平台统计小程序用户")
    @ResponseBody
    public Result getCountNumberByTimeByMp(@RequestParam String time) {
        return ResultUtil.success(userRepository.getCountNumberByTimeByMp(time));
    }

    @RequestMapping(value = "/getCountUser", method = RequestMethod.GET)
    @ApiOperation("根据渠道时间统计用户")
    @ResponseBody
    public Result getCountUser(@RequestParam String time, @RequestParam String platform) {
        return ResultUtil.success(userRepository.getCountUser(time, platform));
    }

    @RequestMapping(value = "/getUserTotal", method = RequestMethod.GET)
    @ApiOperation("管理平台用户分析")
    @ResponseBody
    public Result getUserTotal(@RequestParam String time, @RequestParam String platform, @RequestParam int type) {
        return ResultUtil.success(queryFlows(platform, time, type));
    }

    @RequestMapping(value = "/getOrderTotal", method = RequestMethod.GET)
    @ApiOperation("管理平台订单分析")
    @ResponseBody
    public Result getOrderTotal(@RequestParam String time, @RequestParam String platform, @RequestParam int type, @RequestParam int balance) {
        return ResultUtil.success(totalOrder(platform, time, type, balance));
    }

    @RequestMapping(value = "/getOrderMoneyTotal", method = RequestMethod.GET)
    @ApiOperation("管理平台收入分析")
    @ResponseBody
    public Result getOrderMoneyTotal(@RequestParam String time, @RequestParam String platform, @RequestParam int type, @RequestParam int balance) {
        CommonInfo one = commonRepository.findOne(91);
        if("1".equals(one.getValue())){
            List<PublisherOrderDtoBean> orderList = getOrderList(platform, time, type, balance);
            Map<String, String> map = new HashMap<>();
            String userTotal = "0";//用户提成
            String sqxTotal = "0";//平台提成
            String taunTotal = "0";//团长提成
            for (PublisherOrderDtoBean publisherOrderDtoBean : orderList) {
                String pubSharePreFee = publisherOrderDtoBean.getPub_share_pre_fee();
                if(StringUtils.isNotBlank(pubSharePreFee)){
                    float v = Float.parseFloat(pubSharePreFee) + Float.parseFloat(sqxTotal);
                    sqxTotal = String.valueOf(v);
                }
                String pubSharePreFeeUser = publisherOrderDtoBean.getPub_share_pre_fee_user();
                if(StringUtils.isNotBlank(pubSharePreFeeUser)){
                    float v1 = Float.parseFloat(pubSharePreFeeUser) + Float.parseFloat(userTotal);
                    userTotal = String.valueOf(v1);
                }
                String invitationMoney = publisherOrderDtoBean.getInvitationMoney();
                if(StringUtils.isNotBlank(invitationMoney)){
                    float v2 = Float.parseFloat(invitationMoney) + Float.parseFloat(taunTotal);
                    taunTotal = String.valueOf(v2);
                }
            }
            map.put("userTotal", userTotal);
            map.put("sqxTotal", sqxTotal);
            map.put("taunTotal", taunTotal);
            return ResultUtil.success(map);
        }else{
            List<PublisherOrderDtoBean> orderList = getOrderList(platform, time, type, balance);
            Map<String, String> map = new HashMap<>();
            String userTotal = "0";//用户提成
            String sqxTotal = "0";//平台提成
            String taunTotal = "0";//二级提成
            String taunTota2 = "0";//一级提成
            for (PublisherOrderDtoBean publisherOrderDtoBean : orderList) {
                String pubSharePreFee = publisherOrderDtoBean.getPub_share_pre_fee();
                if(StringUtils.isNotBlank(pubSharePreFee)){
                    float v = Float.parseFloat(pubSharePreFee) + Float.parseFloat(sqxTotal);
                    sqxTotal = String.valueOf(v);
                }
                String pubSharePreFeeUser = publisherOrderDtoBean.getPub_share_pre_fee_user();
                if(StringUtils.isNotBlank(pubSharePreFeeUser)){
                    float v1 = Float.parseFloat(pubSharePreFeeUser) + Float.parseFloat(userTotal);
                    userTotal = String.valueOf(v1);
                }
                String invitationMoney = publisherOrderDtoBean.getInvitationMoney();
                if(StringUtils.isNotBlank(invitationMoney)){
                    float v2 = Float.parseFloat(invitationMoney) + Float.parseFloat(taunTotal);
                    taunTotal = String.valueOf(v2);
                }
                String invitationMoneys = publisherOrderDtoBean.getInvitationMoneys();
                if(StringUtils.isNotBlank(invitationMoneys)){
                    float v2 = Float.parseFloat(invitationMoneys) + Float.parseFloat(taunTota2);
                    taunTota2 = String.valueOf(v2);
                }
            }
            map.put("userTotal", userTotal);
            map.put("sqxTotal", sqxTotal);
            map.put("taunTotal", taunTotal);
            map.put("taunTota2", taunTota2);
            return ResultUtil.success(map);
        }

    }


    private Long queryFlows(String platform, String createAt, int type) {
        // 构造自定义查询条件
        Specification<UserInfo> queryCondition = new Specification<UserInfo>() {
            @Override
            public Predicate toPredicate(Root<UserInfo> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (!platform.equals("all")) {
                    predicateList.add(criteriaBuilder.equal(root.get("platform"), platform));
                }
                if (type != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("isRelation"), type));
                }
                if (createAt != null) {
                    predicateList.add(criteriaBuilder.like(root.get("createAt"), "%" + createAt + "%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return userJpaRepository.count(queryCondition);
    }

    private Long totalOrder(String platform, String createAt, int tk_status, int balance) {
        // 构造自定义查询条件
        Specification<PublisherOrderDtoBean> queryCondition = new Specification<PublisherOrderDtoBean>() {
            @Override
            public Predicate toPredicate(Root<PublisherOrderDtoBean> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (!platform.equals("all")) {
                    predicateList.add(criteriaBuilder.equal(root.get("fromInfo"), platform));
                }
                if (tk_status != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("tk_status"), tk_status));
                }
                if (balance != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("balance"), balance));
                }
                if (createAt != null) {
                    predicateList.add(criteriaBuilder.like(root.get("tk_paid_time"), "%" + createAt + "%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return orderJpaRepository.count(queryCondition);
    }

    private List<PublisherOrderDtoBean> getOrderList(String platform, String createAt, int tk_status, int balance) {
        // 构造自定义查询条件
        Specification<PublisherOrderDtoBean> queryCondition = new Specification<PublisherOrderDtoBean>() {
            @Override
            public Predicate toPredicate(Root<PublisherOrderDtoBean> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<>();
                if (!platform.equals("all")) {
                    predicateList.add(criteriaBuilder.equal(root.get("fromInfo"), platform));
                }//
                if (tk_status != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("tk_status"), tk_status));
                }
                if (tk_status == -1) {
                    predicateList.add(criteriaBuilder.between(root.get("tk_status"),3,12));
                }
                if (balance != -1) {
                    predicateList.add(criteriaBuilder.equal(root.get("balance"),balance));
                }
                if (createAt != null) {
                    predicateList.add(criteriaBuilder.like(root.get("tk_paid_time"), "%" + createAt + "%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
        return orderJpaRepository.findAll(queryCondition);
    }


    //非线程安全实现，需要修改
    static class SingleById {
        static Map<String, Object> map = new HashMap<>();

        static Object getById(String userId) {
            if (map.get(userId) != null) {
                return map.get(userId);
            } else {
                Object object = new Object();
                map.put(userId, object);
                return object;
            }
        }
    }
}
